import { defineStore } from 'pinia'
import { login as loginApi } from '@/services/user'
import router from '@/router'

export const useUserStore = defineStore('user', {
  state: () => ({
    token: '',
    userInfo: {}
  }),
  getters: {
    isLoggedIn: (state) => !!state.token
  },
  actions: {
    async login(loginForm) {
      try {
        const res = await loginApi(loginForm)
        if (res && res['x-token']) {
          this.token = res['x-token']
          localStorage.setItem('token', res['x-token'])
          router.push('/')
          return true
        }
        return false
      } catch (error) {
        console.error('Login failed:', error)
        return false
      }
    },
    logout() {
      this.token = ''
      this.userInfo = {}
      localStorage.removeItem('token')
      router.push('/login')
    }
  },
  persist: {
    key: 'user-store',
    storage: localStorage,
    paths: ['token', 'userInfo']
  }
})